﻿using IdentityServer4.Validation;
using Ids.UserServices;
using System;
using System.Collections.Generic;
using System.Security.Claims;
using System.Threading.Tasks;

namespace Ids.GrantValidators
{
    public class LoginByService : IExtensionGrantValidator
    {
        private readonly IUserService _userService;

        public LoginByService(IUserService userService)
        {
            _userService = userService ?? throw new System.ArgumentNullException(nameof(userService));
        }

        public string GrantType => nameof(LoginByService);

        public async Task ValidateAsync(ExtensionGrantValidationContext context)
        {
            var userName = context.Request.Raw["userName"];
            var password = context.Request.Raw["password"];
            var mac = context.Request.Raw["mac"];

            try
            {
                var uo = await _userService.Login(userName, password, mac);

                var claims = new List<Claim>
                {
                    new Claim(nameof(uo.UserCode),uo.UserCode),
                    new Claim(nameof(uo.Token),uo.Token),
                };

                context.Result = new GrantValidationResult(uo.UserCode, GrantType, claims, "local");
            }
            catch (Exception ex)
            {
                context.Result = new GrantValidationResult(IdentityServer4.Models.TokenRequestErrors.InvalidRequest, ex.Message);
            }

        }
    }
}
